package com.masterlu.leetcode.daily.linkedlist.medium;

import com.masterlu.leetcode.daily.linkedlist.ListNode;

/**
 * 旋转链表
 * https://leetcode-cn.com/problems/rotate-list/
 *
 * @Author：masterlu
 * @Date：2021/4/9 9:39 上午
 */
public class M61RotateRight {

    public ListNode rotateRight(ListNode head, int k) {

        //1.如果k=0，或者原始链表为null或1
        if (k == 0 || head == null || head.next == null) {
            return head;
        }

        //2.统计链表长度
        int size = 1;
        ListNode tmp = head;
        while (tmp.next != null) {
            size++;
            tmp = tmp.next;
        }

        //3.如果移动位置是链表长度整数倍，不用移动
        if (k % size == 0) {
            return head;
        }

        int move = size - k % size;
        //4.链表合并为环
        tmp.next = head;
        while (move-- > 0) {
            tmp = tmp.next;
        }

        //5.移动完成，进行拆环处理
        ListNode newList = tmp.next;
        tmp.next = null;

        return newList;
    }
}
